<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-CN">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  
    
      
    

    
  

  
    
      
    

    
  

  
    
      
    

    
  

  
    
      
    

    
  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Microsoft YaHei:300,300italic,400,400italic,700,700italic|Microsoft YaHei:300,300italic,400,400italic,700,700italic|Microsoft YaHei:300,300italic,400,400italic,700,700italic|Microsoft YaHei:300,300italic,400,400italic,700,700italic|Inziu Iosevka Slab SC:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.2" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="Regular Expression," />








  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.2" />






<meta name="description" content="正则表达式到底是什么东西？在编写处理字符串的程序时，经常会有查找符合某些复杂规则的字符串的需要，正则表达式就是用于描述这些规则的语言。原文：正则表达式 30 分钟入门教程">
<meta name="keywords" content="Regular Expression">
<meta property="og:type" content="article">
<meta property="og:title" content="Regular Expression">
<meta property="og:url" content="http://idmk.oschina.io/2017/08/27/Regular-Expression/index.html">
<meta property="og:site_name" content="苦舟">
<meta property="og:description" content="正则表达式到底是什么东西？在编写处理字符串的程序时，经常会有查找符合某些复杂规则的字符串的需要，正则表达式就是用于描述这些规则的语言。原文：正则表达式 30 分钟入门教程">
<meta property="og:locale" content="zh-CN">
<meta property="og:updated_time" content="2017-11-22T15:33:54.288Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Regular Expression">
<meta name="twitter:description" content="正则表达式到底是什么东西？在编写处理字符串的程序时，经常会有查找符合某些复杂规则的字符串的需要，正则表达式就是用于描述这些规则的语言。原文：正则表达式 30 分钟入门教程">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    sidebar: {"position":"left","display":"hide","offset":12,"offset_float":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: true,
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://idmk.oschina.io/2017/08/27/Regular-Expression/"/>





  <title>Regular Expression | 苦舟</title>
  














</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">苦舟</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">学海无涯，吾将上下求索。</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-commonweal">
          <a href="/404.html" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-heartbeat"></i> <br />
            
            公益404
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://idmk.oschina.io/2017/08/27/Regular-Expression/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="东木金">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/uploads/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="苦舟">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Regular Expression</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-08-27T15:08:20+08:00">
                2017-08-27
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Python/" itemprop="url" rel="index">
                    <span itemprop="name">Python</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h2 id="正则表达式到底是什么东西？"><a href="#正则表达式到底是什么东西？" class="headerlink" title="正则表达式到底是什么东西？"></a>正则表达式到底是什么东西？</h2><p>在编写处理字符串的程序时，经常会有查找符合某些复杂规则的字符串的需要，正则表达式就是用于描述这些规则的语言。<br>原文：<a href="https://deerchao.net/tutorials/regex/regex.htm" target="_blank" rel="external">正则表达式 30 分钟入门教程</a></p>
<a id="more"></a>
<h2 id="元字符"><a href="#元字符" class="headerlink" title="元字符"></a>元字符</h2><table>
<thead>
<tr>
<th style="text-align:center">代码</th>
<th style="text-align:center">说明</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:center"><code>.</code></td>
<td style="text-align:center">匹配除换行符以外的任意字符</td>
</tr>
<tr>
<td style="text-align:center"><code>\w</code></td>
<td style="text-align:center">匹配字母或数字或下划线或汉字</td>
</tr>
<tr>
<td style="text-align:center"><code>\s</code></td>
<td style="text-align:center">匹配任意的空白符</td>
</tr>
<tr>
<td style="text-align:center"><code>\d</code></td>
<td style="text-align:center">匹配数字</td>
</tr>
<tr>
<td style="text-align:center"><code>\b</code></td>
<td style="text-align:center">匹配单词的开始或结束</td>
</tr>
<tr>
<td style="text-align:center"><code>^</code></td>
<td style="text-align:center">匹配字符串的开始</td>
</tr>
<tr>
<td style="text-align:center"><code>$</code></td>
<td style="text-align:center">匹配字符串的结束</td>
</tr>
</tbody>
</table>
<h2 id="字符转义"><a href="#字符转义" class="headerlink" title="字符转义"></a>字符转义</h2><p>如果你想查找元字符本身的话，比如你查找 <code>.</code>, 或者 <code>*</code>, 就出现了问题：你没办法指定它们，因为它们会被解释成别的意思。这时你就得使用 <code>\</code> 来取消这些字符的特殊意义。因此，你应该使用 <code>\.</code> 和 <code>\*</code>。当然，要查找 <code>\</code> 本身，你也得用 <code>\\</code>.</p>
<h2 id="重复"><a href="#重复" class="headerlink" title="重复"></a>重复</h2><table>
<thead>
<tr>
<th style="text-align:center">代码 / 语法</th>
<th style="text-align:center">说明</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:center"><code>*</code></td>
<td style="text-align:center">重复零次或更多次</td>
</tr>
<tr>
<td style="text-align:center"><code>+</code></td>
<td style="text-align:center">重复一次或更多次</td>
</tr>
<tr>
<td style="text-align:center"><code>?</code></td>
<td style="text-align:center">重复零次或一次</td>
</tr>
<tr>
<td style="text-align:center"><code>{n}</code></td>
<td style="text-align:center">重复 n 次</td>
</tr>
<tr>
<td style="text-align:center"><code>{n,}</code></td>
<td style="text-align:center">重复 n 次或更多次</td>
</tr>
<tr>
<td style="text-align:center"><code>{n,m}</code></td>
<td style="text-align:center">重复 n 到 m 次</td>
</tr>
</tbody>
</table>
<h2 id="字符类"><a href="#字符类" class="headerlink" title="字符类"></a>字符类</h2><p>要想查找数字，字母或数字，空白是很简单的，因为已经有了对应这些字符集合的元字符。<br>但是如果你想匹配没有预定义元字符的字符集合 ( 比如元音字母 a,e,i,o,u)，应该怎么办？很简单，你只需要在方括号里列出它们就行了，像 <code>[aeiou]</code> 就匹配任何一个英文元音字母，<code>[.?!]</code> 匹配标点符号 (. 或 ? 或 !)。</p>
<h2 id="分支条件"><a href="#分支条件" class="headerlink" title="分支条件"></a>分支条件</h2><p>正则表达式里的分枝条件指的是有几种规则，如果满足其中任意一种规则都应该当成匹配。<br>具体方法是用 <code>|</code> 把不同的规则分隔开。下面看例子：</p>
<ul>
<li><code>0\d{2}-\d{8}|0\d{3}-\d{7}</code> 这个表达式能匹配两种以连字号分隔的电话号码：一种是三位区号，8 位本地号 ( 如 010-12345678)，一种是 4 位区号，7 位本地号 (0376-2233445)。</li>
<li><code>\(0\d{2}\)[- ]?\d{8}|0\d{2}[- ]?\d{8}</code> 这个表达式匹配 3 位区号的电话号码，其中区号可以用小括号括起来，也可以不用，区号与本地号间可以用连字号或空格间隔，也可以没有间隔。</li>
</ul>
<h2 id="分组"><a href="#分组" class="headerlink" title="分组"></a>分组</h2><p>我们已经提到了怎么重复单个字符（直接在字符后面加上限定符就行了）；但如果想要重复多个字符又该怎么办？你可以用小括号来指定子表达式 ( 也叫做分组 )，然后你就可以指定这个子表达式的重复次数了，你也可以对子表达式进行其它一些操作 ( 后面会有介绍 )。<br>例如：<br><code>(\d{1,3}\.){3}\d{1,3}</code> 是一个简单的 IP 地址匹配表达式。要理解这个表达式，请按下列顺序分析它：<code>\d{1,3}</code> 匹配 1 到 3 位的数字，<code>(\d{1,3}\.){3}</code> 匹配三位数字加上一个英文句号 ( 这个整体也就是这个分组 ) 重复 3 次，最后再加上一个一到三位的数字 <code>(\d{1,3})</code>。不幸的是，它也将匹配 256.300.888.999 这种不可能存在的 IP 地址。<br>如果能使用算术比较的话，或许能简单地解决这个问题，但是正则表达式中并不提供关于数学的任何功能，所以只能使用冗长的分组，选择，字符类来描述一个正确的 IP 地址：<code>((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)</code>。</p>
<h3 id="反义"><a href="#反义" class="headerlink" title="反义"></a>反义</h3><p>有时需要查找不属于某个能简单定义的字符类的字符。比如想查找除了数字以外，其它任意字符都行的情况，这时需要用到反义：</p>
<table>
<thead>
<tr>
<th style="text-align:center">代码 / 语法</th>
<th style="text-align:center">说明</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:center"><code>\W</code></td>
<td style="text-align:center">匹配任意不是字母，数字，下划线，汉字的字符</td>
</tr>
<tr>
<td style="text-align:center"><code>\S</code></td>
<td style="text-align:center">匹配任意不是空白符的字符</td>
</tr>
<tr>
<td style="text-align:center"><code>\D</code></td>
<td style="text-align:center">匹配任意非数字的字符</td>
</tr>
<tr>
<td style="text-align:center"><code>\B</code></td>
<td style="text-align:center">匹配不是单词开头或结束的位置</td>
</tr>
<tr>
<td style="text-align:center"><code>[^x]</code></td>
<td style="text-align:center">匹配除了 x 以外的任意字符</td>
</tr>
<tr>
<td style="text-align:center"><code>[^aeiou]</code></td>
<td style="text-align:center">匹配除了 aeiou 这几个字母以外的任意字符</td>
</tr>
</tbody>
</table>
<p>例子：</p>
<ul>
<li><code>\S+</code> 匹配不包含空白符的字符串。</li>
<li><code>&lt;a[^&gt;]+&gt;</code> 匹配用尖括号括起来的以 a 开头的字符串。</li>
</ul>
<h3 id="后向引用：分组匹配再利用"><a href="#后向引用：分组匹配再利用" class="headerlink" title="后向引用：分组匹配再利用"></a>后向引用：分组匹配再利用</h3><p>使用小括号指定一个子表达式后，匹配这个子表达式的文本（也就是此分组捕获的内容）可以在表达式或其它程序中作进一步的处理。默认情况下，每个分组会自动拥有一个组号，规则是：从左向右，以分组的左括号为标志，第一个出现的分组的组号为 1，第二个为 2 ，以此类推。<br>后向引用用于重复搜索前面某个分组匹配的文本。例如：</p>
<ul>
<li><code>\b(\w+)\b\s+\1\b</code> 可以用来匹配重复且相连的单词，像 <code>go go</code>, 或者 <code>a kitty kitty a</code> 。</li>
</ul>
<p><strong>Python 中不支持指定子表达式的组名</strong><br>你也可以自己指定子表达式的组名。要指定一个子表达式的组名，请使用这样的语法：<code>(?&lt;Word&gt;\w+)</code>( 或者把尖括号换成 <code>&#39;</code> 也行：<code>(?&#39;Word&#39;\w+)</code>), 这样就把 <code>\w+</code> 的组名指定为 <code>Word</code> 了。</p>
<h3 id="反向引用"><a href="#反向引用" class="headerlink" title="反向引用"></a>反向引用</h3><p><strong>Python 中不支持指定子表达式的组名</strong><br>要反向引用分组匹配的内容，你可以使用 <code>\k&lt;Word&gt;</code> ，所以上一个例子也可以写成这样：<code>\b(?&lt;Word&gt;\w+)\b\s+\k&lt;Word&gt;\b</code>。</p>
<h3 id="常用分组语法"><a href="#常用分组语法" class="headerlink" title="常用分组语法"></a>常用分组语法</h3><table>
<thead>
<tr>
<th style="text-align:center">分类</th>
<th style="text-align:center">代码 / 语法</th>
<th style="text-align:center">说明</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:center">匹配</td>
<td style="text-align:center"><code>(exp)</code></td>
<td style="text-align:center">匹配 exp, 并捕获文本到自动命名的组里</td>
</tr>
<tr>
<td style="text-align:center">匹配</td>
<td style="text-align:center"><code>(?&lt;name&gt;exp)</code></td>
<td style="text-align:center">匹配 exp, 并捕获文本到名称为 name 的组里，也可以写成 <code>(?&#39;name&#39;exp)</code></td>
</tr>
<tr>
<td style="text-align:center">匹配</td>
<td style="text-align:center"><code>(?:exp)</code></td>
<td style="text-align:center">匹配 exp, 不捕获匹配的文本，也不给此分组分配组号</td>
</tr>
<tr>
<td style="text-align:center">零宽断言</td>
<td style="text-align:center"><code>(?=exp)</code></td>
<td style="text-align:center">匹配 exp 前面的位置</td>
</tr>
<tr>
<td style="text-align:center">零宽断言</td>
<td style="text-align:center"><code>(?&lt;=exp)</code></td>
<td style="text-align:center">匹配 exp 后面的位置</td>
</tr>
<tr>
<td style="text-align:center">零宽断言</td>
<td style="text-align:center"><code>(?!exp)</code></td>
<td style="text-align:center">匹配后面跟的不是 exp 的位置</td>
</tr>
<tr>
<td style="text-align:center">零宽断言</td>
<td style="text-align:center"><code>(?&lt;!exp)</code></td>
<td style="text-align:center">匹配前面不是 exp 的位置</td>
</tr>
<tr>
<td style="text-align:center">注释</td>
<td style="text-align:center"><code>(?#comment)</code></td>
<td style="text-align:center">这种类型的分组不对正则表达式的处理产生任何影响，用于提供注释让人阅读</td>
</tr>
</tbody>
</table>
<h2 id="Python-Regular-Expression"><a href="#Python-Regular-Expression" class="headerlink" title="Python Regular Expression"></a>Python Regular Expression</h2><p>To avoid any confusion while dealing with regular expressions, we would use Raw Strings as r’expression’.</p>
<h3 id="The-match-Function"><a href="#The-match-Function" class="headerlink" title="The match Function"></a>The <code>match</code> Function</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">import</span> re</div><div class="line"></div><div class="line">line = <span class="string">"Cats are smarter than dogs"</span></div></pre></td></tr></table></figure>
<figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">re.match( <span class="string">r'(.*) are (.*) .*'</span>, line, re.M|re.I)</div></pre></td></tr></table></figure>
<pre><code>&lt;_sre.SRE_Match object; span=(0, 26), match=&apos;Cats are smarter than dogs&apos;&gt;
</code></pre><figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line">matchObj = re.match( <span class="string">r'(.*) are (.*?) .*'</span>, line, re.M|re.I)</div><div class="line">matchObj.group(<span class="number">1</span>), matchObj.group(<span class="number">2</span>)</div></pre></td></tr></table></figure>
<pre><code>(&apos;Cats&apos;, &apos;smarter&apos;)
</code></pre><p>注意：<code>(.*?)</code> 没有问号就不仅仅是捕获到 ‘smarter’</p>
<h3 id="The-search-Function"><a href="#The-search-Function" class="headerlink" title="The search Function"></a>The search Function</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">import</span> re</div><div class="line"></div><div class="line">line = <span class="string">"Cats are smarter than dogs"</span>;</div><div class="line"></div><div class="line">searchObj = re.search( <span class="string">r'(.*) are (.*?) .*'</span>, line, re.M|re.I)</div><div class="line"></div><div class="line"><span class="keyword">if</span> searchObj:</div><div class="line">   print(<span class="string">"searchObj.group() : "</span>, searchObj.group())</div><div class="line">   print(<span class="string">"searchObj.group(1) : "</span>, searchObj.group(<span class="number">1</span>))</div><div class="line">   print(<span class="string">"searchObj.group(2) : "</span>, searchObj.group(<span class="number">2</span>))</div><div class="line"><span class="keyword">else</span>:</div><div class="line">   print(<span class="string">"Nothing found!!"</span>)</div></pre></td></tr></table></figure>
<pre><code>searchObj.group() :  Cats are smarter than dogs
searchObj.group(1) :  Cats
searchObj.group(2) :  smarter
</code></pre><h3 id="Matching-Versus-Searching"><a href="#Matching-Versus-Searching" class="headerlink" title="Matching Versus Searching"></a>Matching Versus Searching</h3><p>Python offers two different primitive operations based on regular expressions: match checks for a match only at the beginning of the string, while search checks for a match anywhere in the string (this is what Perl does by default).</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div></pre></td><td class="code"><pre><div class="line"><span class="comment">#!/usr/bin/python</span></div><div class="line"><span class="keyword">import</span> re</div><div class="line"></div><div class="line">line = <span class="string">"Cats are smarter than dogs"</span>;</div><div class="line"></div><div class="line">matchObj = re.match( <span class="string">r'dogs'</span>, line, re.M|re.I)</div><div class="line"><span class="keyword">if</span> matchObj:</div><div class="line">   print(<span class="string">"match --&gt; matchObj.group() : "</span>, matchObj.group())</div><div class="line"><span class="keyword">else</span>:</div><div class="line">   print(<span class="string">"No match!!"</span>)</div><div class="line"></div><div class="line">searchObj = re.search( <span class="string">r'dogs'</span>, line, re.M|re.I)</div><div class="line"><span class="keyword">if</span> searchObj:</div><div class="line">   print(<span class="string">"search --&gt; searchObj.group() : "</span>, searchObj.group())</div><div class="line"><span class="keyword">else</span>:</div><div class="line">   print(<span class="string">"Nothing found!!"</span>)</div></pre></td></tr></table></figure>
<pre><code>No match!!
search --&gt; searchObj.group() :  dogs
</code></pre><h3 id="Search-and-Replace"><a href="#Search-and-Replace" class="headerlink" title="Search and Replace"></a>Search and Replace</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">import</span> re</div><div class="line"></div><div class="line">phone = <span class="string">"2004-959-559 # This is Phone Number"</span></div><div class="line"></div><div class="line"><span class="comment"># Delete Python-style comments</span></div><div class="line">num = re.sub(<span class="string">r'#.*$'</span>, <span class="string">""</span>, phone)</div><div class="line">print(<span class="string">"Phone Num : "</span>, num)</div><div class="line"></div><div class="line"><span class="comment"># Remove anything other than digits</span></div><div class="line">num = re.sub(<span class="string">r'\D'</span>, <span class="string">""</span>, phone)</div><div class="line">print(<span class="string">"Phone Num : "</span>, num)</div></pre></td></tr></table></figure>
<pre><code>Phone Num :  2004-959-559
Phone Num :  2004959559
</code></pre><p>This method replaces all occurrences of the RE pattern in string with repl, substituting all occurrences unless max provided. This method returns modified string.</p>
<h3 id="Regular-Expression-Modifiers-Option-Flags"><a href="#Regular-Expression-Modifiers-Option-Flags" class="headerlink" title="Regular Expression Modifiers: Option Flags"></a>Regular Expression Modifiers: Option Flags</h3><p>Regular expression literals may include an optional modifier to control various aspects of matching. The modifiers are specified as an optional flag. You can provide multiple modifiers using exclusive OR (|), as shown previously and may be represented by one of these −</p>
<table>
<thead>
<tr>
<th style="text-align:center">Modifier</th>
<th style="text-align:center">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:center">re.I</td>
<td style="text-align:center">Performs case-insensitive matching.</td>
</tr>
<tr>
<td style="text-align:center">re.L</td>
<td style="text-align:center">Interprets words according to the current locale. This interpretation affects the alphabetic group (\w and \W), as well as word boundary behavior (\b and \B).</td>
</tr>
<tr>
<td style="text-align:center">re.M</td>
<td style="text-align:center">Makes $ match the end of a line (not just the end of the string) and makes ^ match the start of any line (not just the start of the string).</td>
</tr>
<tr>
<td style="text-align:center">re.S</td>
<td style="text-align:center">Makes a period (dot) match any character, including a newline.</td>
</tr>
<tr>
<td style="text-align:center">re.U</td>
<td style="text-align:center">Interprets letters according to the Unicode character set. This flag affects the behavior of \w, \W, \b, \B.</td>
</tr>
<tr>
<td style="text-align:center">re.X</td>
<td style="text-align:center">Permits “cuter” regular expression syntax. It ignores whitespace (except inside a set [] or when escaped by a backslash) and treats unescaped # as a comment marker.</td>
</tr>
</tbody>
</table>
<h3 id="doc"><a href="#doc" class="headerlink" title="doc"></a>doc</h3><p><a href="https://www.tutorialspoint.com/python/python_reg_expressions.htm" target="_blank" rel="external">https://www.tutorialspoint.com/python/python_reg_expressions.htm</a></p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Regular-Expression/" rel="tag"># Regular Expression</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2017/08/26/the-AdaBoost-meta-algorithm/" rel="next" title="The AdaBoost Meta-Algorithm">
                <i class="fa fa-chevron-left"></i> The AdaBoost Meta-Algorithm
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2017/08/27/Linear-Regression/" rel="prev" title="Linear Regression">
                Linear Regression <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/uploads/avatar.jpg"
               alt="东木金" />
          <p class="site-author-name" itemprop="name">东木金</p>
           
              <p class="site-description motion-element" itemprop="description">正在学习机器学习，希望能变得很强！</p>
          
        </div>
        <nav class="site-state motion-element">

          
            <div class="site-state-item site-state-posts">
              <a href="/archives/">
                <span class="site-state-item-count">162</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-categories">
              <a href="/categories/index.html">
                <span class="site-state-item-count">18</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-tags">
              <a href="/tags/index.html">
                <span class="site-state-item-count">42</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/bdmk" target="_blank" title="GitHub">
                  
                    <i class="fa fa-fw fa-github"></i>
                  
                    
                      GitHub
                    
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="mailto:catcherchan94@outlook.com" target="_blank" title="E-Mail">
                  
                    <i class="fa fa-fw fa-envelope"></i>
                  
                    
                      E-Mail
                    
                </a>
              </span>
            
          
        </div>

        
        

        
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#正则表达式到底是什么东西？"><span class="nav-number">1.</span> <span class="nav-text">正则表达式到底是什么东西？</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#元字符"><span class="nav-number">2.</span> <span class="nav-text">元字符</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#字符转义"><span class="nav-number">3.</span> <span class="nav-text">字符转义</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#重复"><span class="nav-number">4.</span> <span class="nav-text">重复</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#字符类"><span class="nav-number">5.</span> <span class="nav-text">字符类</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#分支条件"><span class="nav-number">6.</span> <span class="nav-text">分支条件</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#分组"><span class="nav-number">7.</span> <span class="nav-text">分组</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#反义"><span class="nav-number">7.1.</span> <span class="nav-text">反义</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#后向引用：分组匹配再利用"><span class="nav-number">7.2.</span> <span class="nav-text">后向引用：分组匹配再利用</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#反向引用"><span class="nav-number">7.3.</span> <span class="nav-text">反向引用</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#常用分组语法"><span class="nav-number">7.4.</span> <span class="nav-text">常用分组语法</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Python-Regular-Expression"><span class="nav-number">8.</span> <span class="nav-text">Python Regular Expression</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#The-match-Function"><span class="nav-number">8.1.</span> <span class="nav-text">The match Function</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#The-search-Function"><span class="nav-number">8.2.</span> <span class="nav-text">The search Function</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Matching-Versus-Searching"><span class="nav-number">8.3.</span> <span class="nav-text">Matching Versus Searching</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Search-and-Replace"><span class="nav-number">8.4.</span> <span class="nav-text">Search and Replace</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Regular-Expression-Modifiers-Option-Flags"><span class="nav-number">8.5.</span> <span class="nav-text">Regular Expression Modifiers: Option Flags</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#doc"><span class="nav-number">8.6.</span> <span class="nav-text">doc</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy;  2017 - 
  <span itemprop="copyrightYear">2018</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">东木金</span>
</div>


<div class="powered-by">
  由 <a class="theme-link" href="https://hexo.io">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Gemini
  </a>
</div>


        

        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.2"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.2"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.2"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.2"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.2"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.2"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.2"></script>



  


  




	





  





  






  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'manual') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  
    <script type="text/x-mathjax-config">
      MathJax.Hub.Config({
        tex2jax: {
          inlineMath: [ ['$','$'], ["\\(","\\)"]  ],
          processEscapes: true,
          skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
        }
      });
    </script>

    <script type="text/x-mathjax-config">
      MathJax.Hub.Queue(function() {
        var all = MathJax.Hub.getAllJax(), i;
        for (i=0; i < all.length; i += 1) {
          all[i].SourceElement().parentNode.className += ' has-jax';
        }
      });
    </script>
    <script type="text/javascript" src="//cdn.bootcss.com/mathjax/2.7.1/latest.js?config=TeX-AMS-MML_HTMLorMML"></script>
  


  

  

</body>
</html>
